package kt03.rx03

import java.io.File


fun main() {
    val htmlContent = html {
        head {
            "meta" { "charset"("UTF-8") }
        }
        body {
            "div"{
                "style"(
                    """
                      width:666px;
                      height:666px;
                      line-height:600px;
                      background-color:#FFF000;
                      text-align:center
                    """.trimIndent()
                )
                "span"{
                    "style"(
                        """
                        color:white;
                        font-family:Microsoft YaHei
                        """.trimIndent()
                    )
                    +"你好 HTML DSL!!"
                    +"我就是我，不一样的烟火"
                    +"像我这样的人"
                    +"世界上还有几个"
                }
            }
        }
    }.create()



    File("aaa.html").writeText(htmlContent)

}

interface Node {
    fun create(): String
}

class BlockNode(val name: String) : Node {
    val children = ArrayList<Node>()// 节点集合： html head body
    private val properties = HashMap<String, Any>()// 属性集合： style='color: white; font-family: Microsoft YaHei'
    override fun create(): String {
        return """<$name ${properties.map { "${it.key} ='${it.value}'" }.joinToString("")}>${children.joinToString("") { it.create() }}</$name>"""

//      return  """<$name ${properties.map {"${it.key}='${it.value}'" }.joinToString(" ")}>${children.joinToString(""){ it.create() }}</$name>"""
    }

    operator fun String.invoke(action: BlockNode.() -> Unit) {
        val stringNode = BlockNode(this)
        stringNode.action()
        this@BlockNode.children += stringNode
    }

    operator fun String.invoke(value: Any) {
        this@BlockNode.properties[this] = value
    }

    operator fun String.unaryPlus() {
        val stringNode = StringNode("$this&nbsp;&nbsp;")
        this@BlockNode.children += stringNode
    }

}

class StringNode(private val value: String) : Node {
    override fun create(): String = value
}

fun html(action: BlockNode.() -> Unit): BlockNode {
    val html = BlockNode("html")
    html.action()
    return html
}

fun BlockNode.head(action: BlockNode.() -> Unit) {
    val head = BlockNode("head")
    head.action()
    children += head
}

fun BlockNode.body(action: BlockNode.() -> Unit) {
    val body = BlockNode("body")
    body.action()
    children += body
}